var searchApp = angular.module("searchApp",[]);
searchApp.controller("searchController",function($scope, $rootScope, $window, scCodeService, Popup, $location){
	//获取当前城市
	$scope.currentCity=localStorage.getItem("currentCity");
	if($scope.searchHistoryList!="undefined"){
		$scope.currentCity=JSON.parse($scope.currentCity);
	}
	console.log($scope.currentCity);

	//获取历史记录
	$scope.getHistoryList=function () {
		$scope.searchHistoryList=[
			{name:"成都市美年广场1",longitude:"111.123143",latitude:"116.345355",type:"2"},
			{name:"成都市美年广场2",longitude:"",latitude:"",type:"1"},
			{name:"成都市美年广场3",longitude:"111.123143",latitude:"116.345355",type:"2"},
			{name:"成都市美年广场4",longitude:"111.123143",latitude:"116.345355",type:"2"},
			{name:"成都市美年广场5",longitude:"111.123143",latitude:"116.345355",type:"2"},
			{name:"成都市美年广场6",longitude:"111.123143",latitude:"116.345355",type:"2"},
			{name:"成都市美年广场7",longitude:"111.123143",latitude:"116.345355",type:"2"},
			{name:"成都市美年广场8",longitude:"111.123143",latitude:"116.345355",type:"2"},
			{name:"成都市美年广场9",longitude:"111.123143",latitude:"116.345355",type:"2"},
			{name:"成都市美年广场10",longitude:"111.123143",latitude:"116.345355",type:"2"},
			{name:"成都市美年广场11",longitude:"111.123143",latitude:"116.345355",type:"2"},
			{name:"成都市美年广场12",longitude:"111.123143",latitude:"116.345355",type:"2"}
		]
		localStorage.setItem("searchHistoryList",JSON.stringify($scope.searchHistoryList));
		$scope.searchHistoryList=localStorage.getItem("searchHistoryList");
		$scope.historyList=[];
		if($scope.searchHistoryList!="undefined"){
			$scope.searchHistoryList=JSON.parse($scope.searchHistoryList);
			var len=$scope.searchHistoryList.length;
			angular.forEach($scope.searchHistoryList, function(data,index,array){
				if(len-10>0){
					if(index>len-11){
						$scope.historyList.push(array[index]);
					}
				}else{
					$scope.historyList.push(array[index]);
				}
			});
		}
		console.log($scope.historyList);
	}
	$scope.getHistoryList();
	// //清空输入框
	// $scope.searchEmpty = function(){
	// 	$scope.searchVal = ""
	// }
	// $scope.visible = true;
	//根据输入的关键字进行第三方关联地址查询
	$scope.getCognateAddress=function (argument) {
		
		AMap.plugin('AMap.Autocomplete',function(){//回调函数
		    //实例化Autocomplete
		    var autoOptions = {
			    city: $scope.currentCity.cityCode //城市，默认全国
			};
		    autocomplete= new AMap.Autocomplete(autoOptions);
			autocomplete.search($scope.searchVal, function(status, result){
			    //TODO:开发者使用result自己进行下拉列表的显示与交互功能
			    if(status!="error"){
			    	if(status!="no_data"){
					    $scope.CognateAddress=result.tips;
					    $scope.historyList=[];
					    var num=0;
					    var len=$scope.CognateAddress.length;
					    angular.forEach($scope.CognateAddress, function(data,index,array){
							if(len-10>0){
								if(index>len-11){
									$scope.historyList[num]={
										name:array[index].name,
										longitude:'',
										latitude:'',
										type:'3'
									}
									num++;
								}
							}else{
								$scope.historyList[num]={
										name:array[index].name,
										longitude:'',
										latitude:'',
										type:'3'
									}
								num++;
							}
						});
					}
			    }
			});
		})
		
	}
	//清空历史
	$scope.clearHistoryList=function () {
		$scope.historyList=[];
		localStorage.setItem("searchHistoryList","");
	}
	//根据历史记录搜索
	$scope.goToHistorySearch=function (longitude,latitude,name,type) {
		//如无经纬度坐标，就调用根据地址或名称查询站的方法
		if(type=="1"){
			$scope.historyCurrentData={longitude:'',latitude:'',name:name,type:"1"};
			$scope.getStationByName(name);
		}else if(type=="2"){  //若有坐标，就调用根据坐标查询站的方法
			$scope.getStationByCoordinate(longitude,latitude);
			$scope.historyCurrentData={longitude:longitude,latitude:latitude,name:name,type:"2"};
		}else if(type=="3"){  //若是关联地址，则调用第三方根据地址查询坐标
			AMap.service('AMap.Geocoder',function(){//回调函数
			    //实例化Geocoder
			    geocoder = new AMap.Geocoder({
			        city: "010"//城市，默认：“全国”
			    });
			    //TODO: 使用geocoder 对象完成相关功能
			    //地理编码
				geocoder.getLocation(name, function(status, result) {
				    if (status === 'complete' && result.info === 'OK') {
				        //TODO:获得了有效经纬度，可以做一些展示工作
				        $scope.amap=result.geocod.location.split(",");//将查询到的坐标保存起来
				    }else{
				        //获取经纬度失败
				    }
				});
			});
			$scope.getStationByCoordinate($scope.amap[0],$scope.amap[1]);
			$scope.historyCurrentData={longitude:$scope.amap[0],latitude:$scope.amap[1],name:name,type:"2"};
		}
	}
	//根据地址或名称查询站点
	$scope.getStationByName=function(name) {
		var postData={name:name,cityCode:$scope.currentCity.cityCode}
		scCodeService.getStationByName(postData).then(function(data){
			console.log(data.data);
			if(data.code == "200"){
				if(data.data){
					$scope.stationList=data.data;
					console.log($scope.stationList);
					$scope.judgeStationData($scope.stationList);
				}
			}else{
				Popup.notice('搜索站点列表失败', 3000, function() {
	                          console.log('ok')
	                   });
			}
		})
	}
	//根据坐标查询站点
	$scope.getStationByCoordinate=function(longitude,latitude) {
		var postData={longitude:longitude,latitude:latitude}
		scCodeService.getStationByCoordinate(postData).then(function(data){
			console.log(data.data);
			if(data.code == "200"){
				if(data.data){
					$scope.stationList=data.data;
					console.log($scope.stationList);
					//判定数据结果
					$scope.judgeStationData($scope.stationList);
				}
			}else{
				Popup.notice('搜索站点列表失败', 3000, function() {
	                          console.log('ok')
	                   });
			}
		})
	}
	//判断是否存在搜索站点数据，并跳转的问题
	$scope.judgeStationData=function (data) {
		//若存在数据，则保存数据和历史记录，并跳转到站点结果列表页
		if(data!='' && data!=null && data!=undefined){
			$scope.historyList.push($scope.historyCurrentData);
			localStorage.setItem("searchHistoryList",JSON.stringify($scope.historyList));
			localStorage.setItem("stationList",JSON.stringify(data));
			$location.path("/searchResult");
		}else{   //若无数据，则不缓存数据，跳转到无搜索结果页面
			localStorage.setItem("searchHistoryList","");
			$location.path("/noSearchResult");
		}
	}
})

//切换城市
searchApp.controller("checkCityController",function($scope,$element, $rootScope, $window, scCodeService, Popup, $location){
	//获取城市列表
	$scope.getCityList=function () {
		//模拟城市列表展示
		$scope.cityList=[
			{code:"010",name:"北京",letter:"B"},
			{code:"011",name:"鞍山市",letter:"A"},
			{code:"012",name:"安庆市",letter:"A"},
			{code:"013",name:"安阳市",letter:"A"},
			{code:"014",name:"阿拉善盟",letter:"A"},
			{code:"015",name:"成都",letter:"C"},
			{code:"016",name:"鹅毛大雪",letter:"E"},
			{code:"017",name:"大连",letter:"D"}
		]
		scCodeService.getCityList().then(function(data){
			console.log(data.data);
			if(data.code == "200"){
				if(data.data){
					$scope.cityList=data.data;
					console.log($scope.cityList);
				}
			}else{
				Popup.notice('获取城市列表失败', 3000, function() {
	                          console.log('ok')
	                   });
			}
		})
	}
	$scope.getCityList();
	//点击某个城市，储存城市代码和名称并跳转到搜索界面
	$scope.subCurrentCity=function(code,name) {
		console.log(code,name);
		$scope.currentCity={cityCode:code,cityName:name};
		localStorage.setItem("currentCity",JSON.stringify($scope.currentCity));
		$location.path("/search")
	}

	//滑动字母跳转到对应的字母城市列表
	$element.bind("touchstart", onTouchStart);
    function onTouchStart(event) {
        $element.bind("touchmove", onTouchMove);
    }
    function onTouchMove(event) {
        var method = $element.attr("ng-touchmove");
        //$scope.$apply(method);
        var touch = event.touches[0];
		//alert("x:"+Number(touch.clientX)+",y:"+Number(touch.clientY));
		var element = document.elementFromPoint(Number(touch.clientX), Number(touch.clientY));
		//alert(JSON.stringify(element));
		//var element=touch.target;
		var datastr=element.getAttribute("data");
		//alert(datastr)
		console.log(datastr);
		if(datastr!=null && datastr!="null" && datastr.match(/^([A-Z])+$/)){
			console.log("#"+datastr);
			var scrollt=document.getElementById(datastr).offsetTop;
			console.log(scrollt);
			window.scrollTo(0,scrollt);
			//window.location.href="#/checkCity#"+datastr;
		}
    }
	
})